﻿using BSWDEEPLEARNWrapper;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Station.Inspect.SuaModel
{
	class ModelBswClass:ModelBase
    {
		private bswClassEvaluator model;
		int net_width = 256;
		int net_height = 256;
		void ClearModel()
		{
			if(model !=null)
            {
				model.ClassRelease();
				model = null;
            }
			minID = -1;
			maxID = -1;
		}

		public bool LoadModel(string fileName)
		{
			ClearModel();
			if (TryParseName(fileName) == false)
				return false;
			model = new bswClassEvaluator(fileName, 0, true);
			if(model.status != ClassStatus.Cls_Success)
            {
				return false;
            }
			bool isWarmup = model.Warmup(5);
			if (!isWarmup)
			{
				//Log.Instance.Error($"节点[{Name}]分割模型显卡热身失败");
				return false;
			}
			return true;
		}

		public bool Run(Bitmap img,int cx,int cy,double threshold)
        {
			//if (res == null)
			bool bNG = true;
			if (model != null)
            {
				int ClassL = cx - net_width / 2;
				int ClassT = cy - net_height / 2;
				int ClassR = ClassL + net_width;
				int ClassB = ClassT + net_height;
				if (ClassL < 0)
					ClassL = 0;
				if (ClassT < 0)
					ClassT = 0;
				if (ClassR > img.Width - 1)
					ClassR = img.Width - 1;
				if (ClassB > img.Height - 1)
					ClassB = img.Height - 1;
				Bitmap bmp = img.Clone(new Rectangle(ClassL, ClassT, ClassR - ClassL, ClassB - ClassT),System.Drawing.Imaging.PixelFormat.Format24bppRgb);
				if(bmp !=null)
                {
					var bi = GetImagePixel(bmp);
					var res = new List<ClassResult>();
					bool Result = model.ClassEvaluate(bi.Result, bi.width, bi.height, bi.Channels, bi.Stride, res);
					if(Result)
                    {
						bNG = res.Find(p => (p.name == "NG" && p.prob > threshold) || (p.name == "OK" && p.prob < 0.9)) != null;
					}
				}
			}
			return bNG;
		}

		//private static BitmapInfo GetImagePixel(Bitmap Source)
		//{
		//	//byte[] result;
		//	int step;
		//	int iWidth = Source.Width;
		//	int iHeight = Source.Height;

		//	Rectangle rect = new Rectangle(0, 0, iWidth, iHeight);
		//	System.Drawing.Imaging.BitmapData bmpData = Source.LockBits(rect,
		//		System.Drawing.Imaging.ImageLockMode.ReadWrite, Source.PixelFormat);
		//	IntPtr iPtr = bmpData.Scan0;
		//	//int iBytes = iWidth * iHeight * 3;
		//	step = bmpData.Stride / iWidth;
		//	int iStride = bmpData.Stride;
		//	//int iBytes = iWidth * iHeight * step;
		//	int iBytes = Math.Abs(bmpData.Stride) * iHeight;
		//	byte[] PixelValues = new byte[iBytes];
		//	System.Runtime.InteropServices.Marshal.Copy(iPtr, PixelValues, 0, iBytes);
		//	Source.UnlockBits(bmpData);
		//	// result = PixelValues;
		//	BitmapInfo bi = new BitmapInfo { Result = PixelValues, Channels = step, Stride = iStride, width = iWidth, height = iHeight };
		//	return bi;
		//}
	}
}
